import React, { memo, useCallback, useMemo, useState } from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types';
import { Upload, message } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';

const UploadControl = ({ img, callback }) => {
  const [uploading, setUploading] = useState(false);
  const [imageUrl, setImageUrl] = useState(img);

  const uploadButton = useMemo(
    () => (
      <div style={{ color: '#dedede' }}>
        {uploading ? <LoadingOutlined /> : <PlusOutlined />}
        <div>上传</div>
      </div>
    ),
    [uploading],
  );

  const beforeUpload = useCallback((file) => {
    const imgTypes = ['image/jpeg', 'image/png', 'image/jpg'];
    const isJPG = _.includes(imgTypes, file.type);

    if (!isJPG) {
      message.error('仅允许上传的文件类型JPG,JPEG,PNG!');
    }
    const isLt20M = file.size / 1024 / 1024 < 20;
    if (!isLt20M) {
      message.error('文件大小不能超过20MB!');
    }
    if (isJPG && isLt20M) {
      previewAndUpload(file);
    }
    return false;
  }, []);

  const previewAndUpload = (img) => {
    setUploading(true);
    const reader = new FileReader();
    reader.addEventListener('load', () => {
      setUploading(false);
      setImageUrl(reader.result);
      // fire parent callback
      callback(img);
    });
    reader.readAsDataURL(img);
  };

  return (
    <Upload
      name="file"
      showUploadList={false}
      listType="picture-card"
      beforeUpload={beforeUpload}
    >
      {imageUrl ? (
        <img src={imageUrl} alt="Logo" style={{ width: '100%' }} />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};

UploadControl.propTypes = {
  callback: PropTypes.func.isRequired,
  img: PropTypes.string,
};

export default memo(UploadControl);
